<template>
  <a-card :bordered="false">
    <!-- 快捷查询 -->
    <div class="c-container">
      <a-row>
        <a-col :xl="8" :lg="8" :md="8" :sm="24">
          <a-menu v-model="current" mode="horizontal" @select="selectType">
            <a-menu-item key="submit">
              <span class="title actived">申请激活</span>
            </a-menu-item>
            <a-menu-item key="silent">
              <span class="title">全部</span>
            </a-menu-item>
            <a-menu-item key="delete">
              <span class="title">回收站 </span>
            </a-menu-item>
          </a-menu>
        </a-col>
        <a-col :xl="10" :lg="10" :md="10" :sm="24">
          <div class="searchBox">
            <a-input-search
              placeholder="请输入商机名称"
              v-model="queryParam.businessName"
              enter-button="搜索"
              size="default"
              @keyup.enter.native="searchQuery"
              @search="searchQuery"
            />
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <oufu-scene-slider
        ref="oufuSlider"
        :title="sliderTitle"
        :sceneType="sceneType"
        :columns="columns"
      ></oufu-scene-slider>
      <div>
        <span style="margin: 0 5px">产品品类： </span>
        <j-dict-select-tag
          style="width: 200px"
          placeholder="请选择产品品类"
          v-model="queryParam.productCategory"
          :triggerChange="true"
          @change="productCateChange"
          dictCode="DataDictionary,description,dictionaryId, dictionaryTypeId =PRODUCT_CATEGORY"
        />
      </div>

     <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="3" @click="batchActivate"><a-icon type="edit" />激活</a-menu-item>
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
           <!-- <a-menu-item key="2" @click="handleExportXls('商机表')"><a-icon type="download" />导出</a-menu-item>-->
        </a-menu>
        <a-button> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown> 
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ x: 1200 }"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="businessName" slot-scope="text, record">
          <a-tooltip placement="top">
            <template slot="title">
              <span>{{ record.businessName }}</span>
            </template>
            <span class="ellipsis"
              >
              <a @click="() => handleReadDrawer(record)">{{ record.businessName }}</a>
              </span
            >
          </a-tooltip>
        </template>
        <span slot="followup" slot-scope="followup, record"> {{ record.followup }}% </span>
        <span slot="action" slot-scope="text, record">
           <a-popconfirm title="确定驳回吗?" @confirm="handleOperate(record, '1')">
            <a>驳回</a>
          </a-popconfirm>

          <a-divider type="vertical" />

          <a-dropdown>
            <a class="ant-dropdown-link">
              更多
              <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a-popconfirm title="确定激活吗?" @confirm="handleOperate(record, '3')">
                  <a>激活</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="handleOperate(record, '4')">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <crmBusiness-modal-drawer
      ref="modalFormDrawer"
      @handleDelete="handleDelete"
      @handleEdit="handleEdit"
    ></crmBusiness-modal-drawer>
  </a-card>
</template>


<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { MonthsBetw, getNowDate, compareDate } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CrmBusinessModal from './modules/CrmBusinessModal'
import CrmBusinessModalDrawer from './modules/CrmBusinessModal__Style#Drawer'
import moment from 'moment'
import OufuSceneSlider from '@/components/jeecg/OufuSceneSlider.vue'
import JSearchSelectTag from '@/components/dict/JSearchSelectTag'
import { httpAction, getAction } from '@/api/manage'
import { mapGetters } from 'vuex'

function number_format(number, decimals, dec_point, thousands_sep) {
  /*
   * 参数说明：
   * number：要格式化的数字
   * decimals：保留几位小数
   * dec_point：小数点符号
   * thousands_sep：千分位符号
   * */
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep,
    dec = typeof dec_point === 'undefined' ? '.' : dec_point,
    s = '',
    toFixedFix = function (n, prec) {
      var k = Math.pow(10, prec)
      return '' + Math.ceil(n * k) / k
    }

  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
  var re = /(-?\d+)(\d{3})/
  while (re.test(s[0])) {
    s[0] = s[0].replace(re, '$1' + sep + '$2')
  }

  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }
  return s.join(dec)
}
export default {
  name: 'CrmBusinessList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    CrmBusinessModal,
    OufuSceneSlider,
    CrmBusinessModalDrawer,
    moment,
    JSearchSelectTag,
  },
  data() {
    return {
      sliderTitle: '团队',
      description: '商机表管理页面',
      current: ['submit'],
      //场景定义开始
      sceneType: 'CrmBusiness',
      //场景定义结束
      queryParam: {
        // ownerUserId: this.userInfo().userLoginId,
        productCategory: '',
        infoStatusId: '2',
        isManage: 'Y'
      },
      isorter: {
        column: 'updateTime',
        order: 'desc',
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'left',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
          fixed: 'left',
        },
        {
          title: '商机名称',
          align: 'center',
          width: 200,
          sorter: (a, b) => a.businessName - b.businessName,
          dataIndex: 'businessName',
          scopedSlots: { customRender: 'businessName' },
          fixed: 'left',
        },
        {
          title: '客户名称',
          width: 220,
          align: 'center',
          sorter: (a, b) => a.customerId_dictText - b.customerId_dictText,
          dataIndex: 'customerId_dictText',
          ellipsis: true,
        },
        {
          title: '商机状态',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'infoStatusId_dictText',
        },
        {
          title: '客户经理',
          align: 'center',
          sorter: (a, b) => a.ownerUserId_dictText - b.ownerUserId_dictText,
          dataIndex: 'ownerUserId_dictText',
          width: 150,
          ellipsis: true,
        },
        {
          title: '商机类型',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'typeId_dictText',
        },
        {
          title: '仓库',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'warehouseName',
        },
        {
          title: '冷冻',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedFreeze',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '冷藏',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedRefrigerate',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '恒温',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedConstant',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '常温',
          width: 200,
          ellipsis: true,
          align: 'center',
          dataIndex: 'estimatedNormal',
          customRender: function (t, r, index) {
            return number_format(t, 0, '.', ',')
          },
        },
        {
          title: '商机阶段',
          align: 'center',
          sorter: (a, b) => a.statusId_dictText - b.statusId_dictText,
          dataIndex: 'statusId_dictText',
          width: 150,
        },
        {
          title: '更新时间',
          align: 'center',
          sorter: (a, b) => a.updateTime - b.updateTime,
          dataIndex: 'updateTime',
          width: 200,
        },
        {
          title: '操作',
          width: 175,
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
          fixed: 'right',
        },
      ],
      url: {
        list: '/online/api/pagingCrmBusiness',
        delete: '/online/api/deleteCrmBusiness',
        deleteBatch: '/online/api/deleteCrmBusinessBatch',
        exportXlsUrl: '/online/api/exportCrmBusinessXls',
        importExcelUrl: '/online/api/importCrmBusinessExcel',
        sceneList: '/online/api/pagingCrmScene',
        createCrmStar: '/online/api/createCrmStar',
        setBusinessLastRemindTime: '/online/api/setBusinessLastRemindTime',
        setCrmBusinessStatus: '/online/api/setCrmBusinessStatus',
      },
      dictOptions: {},
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    getNowDate() {
      var date = new Date()
      let year = date.getFullYear() //获取完整的年份(4位)
      let month = date.getMonth() + 1 //获取当前月份(0-11,0代表1月)
      let day = date.getDate() //获取当前日(1-31)
      if (month < 10) {
        month = '0' + month
      }
      if (day < 10) {
        day = '0' + day
      }
      return year + '-' + month + '-' + day
    },
    ...mapGetters(['userInfo']),
    initDictConfig() {
      const that = this
      this.$bus.on('superParam', function (param) {
        this.queryParam
        if (param.type == 1) {
          that.superQueryParams = ''
          that.superQueryFlag = false
          if (param.data != 0) {
            that.queryParam.ownerUserIdList = param.data
            that.loadData(1)
          } else {
            delete that.queryParam.ownerUserIdList
            that.loadData(1)
          }
        }
        if (param.type == 2) {
          //高级查询方法
          if (!param.data) {
            that.superQueryParams = ''
            that.superQueryFlag = false
          } else {
            that.superQueryFlag = true
            that.superQueryParams = JSON.stringify(param.data)
          }
          that.loadData(1)
        }
      })
    },
    batchActivate: function () {
      let that = this;
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！');
        return;
      } else {
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        this.$confirm({
          title: "确认激活",
          content: "是否激活选中数据?",
          onOk: function () {
            that.loading = true
            getAction(that.url.setCrmBusinessStatus, { id: ids, infoStatusId: '3' })
              .then((res) => {
                if (res.success) {
                  that.loading = false
                  that.loadData()
                  that.$message.success('操作成功!')
                }
              })
              .catch(() => {
                that.loading = false
              })
          }
        });
      }
    },


    selectType(e) {
      this.$emit('menu-select', e)
    },
    reload(e) {
      this.$refs.modalFormDrawer.edit(e)
    },
    productCateChange(e) {
      this.queryParam.productCategory = e
      this.loadData()
    },
    handleReadDrawer(record) {
      record.isEditBusiness = false
      this.handleViewDrawer(record)
    },
    //批量激活
    handleOperate(record,e){
      this.loading = true
      getAction(this.url.setCrmBusinessStatus, { id: record.id, infoStatusId: '3' })
        .then((res) => {
          if (res.success) {
            this.loading = false
            this.loadData()
            this.$message.success('操作成功!')
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
@import '~@assets/less/pageHead.css';
.c-container .actived {
  color: #168a40;
}
.c-container .ant-menu-item-active {
  border-bottom-color: #168a40;
}
.c-container .ant-menu-item-selected {
  border-width: 3px;
  border-bottom-color: #168a40;
}
</style>
<style lang="less" scoped>
/deep/ .ant-input-search-button{
  background-color:#168a40;
  border-color:#168a40;
}
.ellipsis {
  width: 184px;
}
</style>